﻿using AutoMapper;
using CarAppDomain.CarType.Entities;
using CarAppDomain.CarType.IRepository;
using CarAppDomain.CarType.IService;
using CarAppDto.CarType.CountryDtos;
using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.Utils;
using D.UtilSqlsugarOrm;
using System.Linq.Expressions;
using CarAppDto.Dtos;

namespace CarAppDomain.CarType.Service
{
    public class CountryService : BaseService<CountryEntity>,ICountryService
    {
        private readonly IMapper _mapper;
        private readonly ICacheService _cache;
        private readonly ICountryEntityRepository _repository;
        private readonly IAreaEntityRepository _repositoryArea;

        /// <summary>
        /// 构造注入
        /// </summary>
        public CountryService(IMapper mapper, ICacheService cache, ICountryEntityRepository repository, IAreaEntityRepository repositoryArea)
        {
            // 用于base方法
            base._baseDal = repository;
            this._repository = repository;
            _cache = cache;
            _mapper = mapper;
            _repositoryArea = repositoryArea;
        }

        #region 增删改查


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddCountryAsync(ReqAddCountry reqModel)
        {
            var exists = await _repository.ExistsAsync(m => m.Name == reqModel.Name);
            if (exists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "名称重复" };
            }
            var areaExists = await _repositoryArea.ExistsAsync(m => m.Id==reqModel.AreaId);
            if (!areaExists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "区域不存在" };
            }
            var insertEntity = _mapper.Map<ReqAddCountry,CountryEntity>(reqModel);
            insertEntity.DeleteFlag = false;
            insertEntity.CreateTime = DateTime.Now;
            insertEntity.UpdateTime = DateTime.Now;
            insertEntity.Id = Guid.NewGuid().ToString();
            var dbres = await _repository.AddAsync(insertEntity);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteCountryAsync(List<string> ids)
        {
            var dbres = await _repository.DeleteAsync(m => ids.Contains(m.Id));
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> UpdateCountryAsync(ReqUpdateCountry reqModel)
        {

            var updateEntity = await _repository.GetModelAsync(m => m.Id == reqModel.Id);
            if (updateEntity == null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "该信息不存在" };
            }
            var exists = await _repository.ExistsAsync(m =>m.Id!=reqModel.Id&&( m.Name == reqModel.Name));
            if (exists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "名称重复" };
            }
            var areaExists = await _repositoryArea.ExistsAsync(m => m.Id == reqModel.AreaId);
            if (!areaExists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "区域不存在" };
            }
            updateEntity.Name= reqModel.Name;
            updateEntity.EnglishName = reqModel.EnglishName;
            updateEntity.UpdateTime = DateTime.Now;
            updateEntity.UpdateUser = reqModel.UpdateUser;
            updateEntity.AreaId = reqModel.AreaId;
            updateEntity.Code = reqModel.Code;
            var dbres = await _repository.UpdateAsync(updateEntity);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<RepCountry>>> QueryCountryListAsync(ReqQueryCountryList reqModel)
        {
            Expression<Func<CountryEntity, bool>> where = null;
            if (!string.IsNullOrEmpty(reqModel.Name))
            {
                where = where.And(m => m.Name.Contains(reqModel.Name));
            }

            if (!string.IsNullOrEmpty(reqModel.EnglishName))
            {
                where = where.And(m => m.EnglishName.Contains(reqModel.EnglishName));
            }
            if (!string.IsNullOrEmpty(reqModel.AreaId))
            {
                where = where.And(m => m.AreaId==reqModel.AreaId);
            }

            var dbres = await _repository.GetListAsync(where);
            var res = _mapper.Map<List<CountryEntity>, List<RepCountry>>(dbres);
            return res.GetResponse();
        }

        /// <summary>
        /// 获取用户分页
        /// </summary>
        /// <param name="reqQueryAdminPage"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageModel<RepCountry>>> QueryCountryPagesAsync(ReqQueryCountryPage reqQueryPage)
        {
            Expression<Func<CountryEntity, bool>> where = null;
            if (!string.IsNullOrEmpty(reqQueryPage.Name))
            {
                where = where.And(m => m.Name.Contains(reqQueryPage.Name));
            }

            if (!string.IsNullOrEmpty(reqQueryPage.EnglishName))
            {
                where = where.And(m => m.EnglishName.Contains(reqQueryPage.EnglishName));
            }

            if (!string.IsNullOrEmpty(reqQueryPage.AreaId))
            {
                where = where.And(m => m.AreaId == reqQueryPage.AreaId);
            }

            Expression <Func<CountryEntity, object>> order = null;
            bool orderByAsc = true;
            if (reqQueryPage.Sorts!=null&&reqQueryPage.Sorts?.Count != 0)
            {
                SortDto sortDtoFrist= reqQueryPage.Sorts.FirstOrDefault();
                string sortField = sortDtoFrist?.Field;
                string sortOrder = sortDtoFrist?.Sort;
                order = ExpressionUtil.GetOrderObjectExpression<CountryEntity>(sortField, sortOrder, ref orderByAsc);
            }
            else
                order = m => m.CreateTime;
            
           var dbres = await _repository.GetOrderPagesAsync(reqQueryPage.PageSize, reqQueryPage.PageNo, where, order, orderByAsc);
            var res = new PageModel<RepCountry>()
            {
                PageNo = dbres.PageNo,
                PageSize = dbres.PageSize,
                TotalCount = dbres.TotalCount,
                TotalPage = dbres.TotalPage,
                Data = _mapper.Map<List<CountryEntity>, List<RepCountry>>(dbres.Data)
            };
            return res.GetResponse();
        }

        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<RepCountry>> GetCountryAsync(string id)
        {
            var dbres = await _repository.GetModelAsync(m => m.Id == id);
            var res = _mapper.Map<CountryEntity, RepCountry>(dbres);
            return res.GetResponse();
        }

        #endregion
    }
}
